// 应用设置
import settings from '@/settings'
import localStorage from '@/utils/localStorage'
import cookie from '@/utils/cookie'
import { getQueryStringRegExp } from '@/utils/data'
import { getUserInfo, login, logout, register } from '@/api/auth'
import { logout as logoutH4a } from '@/api/h4aOauth'
import router from '@/router'

let { tokenName, tokenExpires, tokenStoreWay, menuType } = settings

// function getRt(url, index) {
//   let fateRt = url.slice(index),
//       equalIndex = fateRt.indexOf('=')
//   fateRt = fateRt.slice(equalIndex + 1)
//   let $index = fateRt.indexOf('&')
//   return $index === -1
//       ? fateRt
//       : fateRt.slice(0, $index)
// }

function getRtFromUrl() {
  let token = getQueryStringRegExp('token') || getQueryStringRegExp('refresh_token')
  if (token) {
    let index = token.indexOf('#/')
    if (index !== -1) {
      token = token.slice(0, index)
    }
    return token
  }
  return undefined
}

function setTokenLocal(token) {
  if (tokenStoreWay === 'localStorage') {
    localStorage.setLocalStorage(tokenName, token, tokenExpires)
  } else if (tokenStoreWay === 'cookie') {
    cookie.setCookie(tokenName, token, tokenExpires)
  }
}

function initToken(tokenName) {
  // 从 url 获取 token等
  let rt = getRtFromUrl()
  if (rt) {
    setTokenLocal(rt)
    // 将 token 从 url 上删除
    let querys = location.href.split('?')[1].split('&')
    let newQuery = querys
      .filter(item => {
        let key = item.split('=')[0].trim()
        return key != 'token' && key != 'refresh_token'
      })
      .join('&')
    if (newQuery) {
      location.href = location.href.split('?')[0] + '?' + newQuery
    } else {
      location.href = location.href.split('?')[0]
    }
    return rt
  } else {
    return localStorage.getLocalStorage(tokenName) || cookie.getCookie(tokenName)
  }
}

function inIframe() {
  try {
    return window.self !== window.top
  } catch (e) {
    return true
  }
}

const state = () => ({
  lang: cookie.getCookie('epLang') || 'zh',
  authorization: initToken(tokenName),
  isOauth: false,
  appLoading: false,
  appError: false,
  userInfo: null,
  userMainInfo: {
    loginId: '',
    username: '',
    email: '',
    mobile: '',
    roles: [],
    type: '',
    orgName: '',
    orgCode: ''
  },
  routeKeepAlive: [],
  epinConfig: {},
  webviewType: null, // 1 - 没菜单和头
  isInIFrame: inIframe() // 是否在 iframe 中
})
// getters
const getters = {
  token: state => {
    return state.authorization
  },
  isOauth: state => {
    return state.isOauth
  }
}

// actions
const actions = {
  setRefreshToken({ commit, state, dispatch }, token) {
    commit('SETAUTHORIZATION', token)
  },

  login({ commit, state, dispatch }, body) {
    return login(body)
      .then(res => {
        let { data } = res
        if (data.data.hunterToken) {
          commit('SETAUTHORIZATION', data.data.hunterToken)
        }
        if (menuType === 'static' && settings.routePermission === 'allPass') {
          dispatch('menu/setMenuJSONStatic', null, { root: true })
        }
        return Promise.resolve(res.data)
      })
      .catch(err => {
        console.log(err)
        return Promise.reject(err.data)
      })
  },
  logout({ commit, state, dispatch }) {
    if (localStorage.getLocalStorage('lastTokenType') == 'H4a') {
      commit('SETAUTHORIZATION', null)
      commit('SETUSERINFO', null)
      commit('SETISOAUTH', null)
      logoutH4a()
      return Promise.resolve()
    } else {
      logout().then(res => {
        commit('SETAUTHORIZATION', null)
        commit('SETUSERINFO', null)
        commit('SETISOAUTH', null)
        // dispatch('menu/setMenuJSON', [], { root: true })
        router.push('/login')
        localStorage.setLocalStorage('lastTokenType', 'hunterToken')
        return Promise.resolve()
      })
    }
  },
  register({ commit, state, dispatch }, body) {
    return register(body)
      .then(res => {
        let { data } = res
        return Promise.resolve(data)
      })
      .catch(err => {
        console.log(err)
        return Promise.reject(err.data)
      })
  },
  async getUserInfo({ commit, state, dispatch }) {
    commit('SETAPPLOADING', false)
    return getUserInfo()
      .then(res => {
        console.log(res)
        commit('SETUSERINFO', res.data)
        commit('SETUSERMAININFO', res.data)
        // if (menuType === 'api') {
        //   dispatch('menu/setMenuJSON', res.data.menus, { root: true })
        // }
        // if (menuType === 'static') {
        //   dispatch('menu/setMenuJSONStatic', null, { root: true })
        // }
        // commit('SETAPPLOADING', true)
        // return Promise.resolve(res)
      })
      .catch(err => {
        commit('SETAPPLOADING', false)
        return Promise.reject(err)
      })
  }
}

// mutations
const mutations = {
  SETISOAUTH(state, data) {
    state.isOauth = data
  },
  SETAUTHORIZATION(state, data) {
    if (data === null) {
      // remove
      state.authorization = null
      localStorage.delLocalStorage(tokenName)
      cookie.delCookie(tokenName)
    } else {
      // set
      state.authorization = data
      setTokenLocal(data)
    }
  },

  SETAPPLOADING(state, data) {
    state.appLoading = data
  },
  SETAPPERROR(state, data) {
    state.appError = data
  },
  SETUSERINFO(state, data) {
    state.userInfo = data
  },
  SETUSERMAININFO(state, data) {
    let { userLoginId, userName, admin } = data
    // roles = roles ? roles : {}
    // userInfo = userInfo ? userInfo : {}
    // orgInfo = orgInfo ? orgInfo : {}
    console.log(data)
    state.userMainInfo = {
      loginId: userLoginId,
      username: userName,
      type: admin ? 'admin' : 'normal'
      // email: userInfo.email,
      // mobile: userInfo.mobile,
      // roles: roles,
      // type: userInfo.userType,
      // orgName: orgInfo.orgName,
      // orgCode: orgInfo.orgCode
    }
  },
  SETROUTEKEEPALIVE(state, data) {
    state.routeKeepAlive = data
  },
  SETLANG(state, data) {
    // Vue.prototype.$i18n.locale = data not work
    state.lang = data
    cookie.setCookie('epLang', data, 365)
  },
  SETTOKENFROMURL(state, data) {
    let rt = getRtFromUrl()
    console.log(rt)
    if (rt) {
      state.authorization = rt
    }
  },
  SETWEBVIEWTYPE(state, data) {
    state.webviewType = data
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
